from django.shortcuts import render, HttpResponse, redirect
from django.views import View

from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required


# Create your views here.

def index(request):
    if request.user.username:
        return render(request, 'index_mylogin.html', {'user': request.user.username})
    else:
        return redirect('mylogin:loginx')


class Myregister(View):

    def get(self, request):
        return render(request, 'myregister.html')

    def post(self, request):
        username = request.POST.get('username', '')
        email = request.POST.get('email', '')
        password = request.POST.get('password', '')

        # 注册到数据库
        # User.objects.create() 一般的创建模型方法 --保存原字段
        # User.objects.create_user() # 密码会加密, 用户是一般用户
        # User.objects.create_superuser() # 密码会加密, 用户是超级用户
        # User.objects.create(username=username,email=email,password=password)
        # User.objects.create_user(username=username,email=email,password=password)
        User.objects.create_superuser(username=username, email=email, password=password)

        return HttpResponse('注册成功')


from django.db.models import Q


class Loginx(View):
    def get(self, request):
        return render(request, 'loginx.html')

    def post(self, request):
        username = request.POST.get('username', '1')
        password = request.POST.get('password', '1')

        # 认证通过
        # user = authenticate(username=username, password=password)
        authentication = CustomBackend()
        user = authentication.authenticate(username=username, password=password)
        # print(user)
        # print(user.username)
        if user:
            # login(request, user, backend='django.contrib.auth.backends.ModelBackend')
            login(request, user)
            return redirect("mylogin:index")
        else:
            return HttpResponse("认证失败!")
        # print('--------->',user)
        # print(type(user))
        # print(user.email)
        # 将user绑定到request

        return redirect('mylogin:index')


def logoutx(request):
    # 将认证id 从request中删除
    logout(request)
    return HttpResponse('注销成功')


# @login_required(login_url='/mylogin/loginx/')
# def secret(request):
#     return HttpResponse("这个界面需要登录才能看到")
@login_required
def secret(request):
    return HttpResponse("这个界面需要登录才能看到")


from django.contrib.auth.backends import ModelBackend


class CustomBackend(ModelBackend):
    def authenticate(self, username=None, password=None, **kwargs):
        try:
            print(username, password)
            user = User.objects.get(Q(username=username) | Q(email=username))

            if user.check_password(password):
                return user
        except Exception as e:
            print(e)
            return None
